package com.taikang.common.util;

import java.text.SimpleDateFormat;
import java.util.EmptyStackException;


/*
 * 身份证合法校验
 * 
 * @Author WangHuan
 * */

public class IdentificationCodeUtil {
	  
	private final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
	private final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
	private int[] ai = new int[18];

	public boolean Verify(String idcard) 
	{
		try 
		{
			if (idcard.length() == 15) {
				idcard = upToEighteen(idcard);
				System.out.println("15位转为18位:" + idcard);
			}
			if (idcard.length() != 18) {
				System.out.println("错误！身份证号码不是18位！");
				return false;
			}
			String verify = idcard.substring(17, 18);
			String birth = idcard.substring(6, 10) + "-"
					+ idcard.substring(10, 12) + "-" + idcard.substring(12, 14);
			//加入生日类型验证
			if(isRightDate(birth) == false)
			{
				System.out.println("错误！ 生日非法！");
				return false;
			}
			
			
			
			if (verify.equals(getVerify(idcard))) 
			{
				if (Integer.parseInt(idcard.substring(16, 17)) % 2 == 1)
				{
					System.out.println("正确! 出生日期：" + birth + "性别:男;");
					return true; 
				}else{
					System.out.println("正确! 出生日期：" + birth + "性别:女;");
					return true; 
				}	
			}
			System.out.println("错误！");
			return false;
		} catch (EmptyStackException e) {
			return false;
		}
	}

	private boolean isRightDate(String date)
	{
		try{
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		    dateFormat.setLenient(false);
		    dateFormat.parse(date);
		    return true;
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}
	// get verify
	private String getVerify(String eighteenCardId) 
	{
		int remaining = 0;
		if (eighteenCardId.length() == 18) {
			eighteenCardId = eighteenCardId.substring(0, 17);
		}
		if (eighteenCardId.length() == 17) {
			int sum = 0;
			for (int i = 0; i < 17; i++) {
				String k = eighteenCardId.substring(i, i + 1);
				ai[i] = Integer.parseInt(k);
			}
			for (int i = 0; i < 17; i++) {
				sum = sum + wi[i] * ai[i];
			}
			remaining = sum % 11;
		}
		return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
	}

	// 15 update to 18
	public String upToEighteen(String fifteenCardId) {
		String eighteenCardId = fifteenCardId.substring(0, 6);
		eighteenCardId = eighteenCardId + "19";
		eighteenCardId = eighteenCardId + fifteenCardId.substring(6, 15);
		eighteenCardId = eighteenCardId + getVerify(eighteenCardId);
		return eighteenCardId;
	}
	
	public static  void main(String[] args)
	{
		IdentificationCodeUtil icu = new IdentificationCodeUtil();
		String[] codeArray = new String[]{"132232770616402","110102830401193","123456789012345","110102195303031987"}; 
		for(int i = 0 ; i < codeArray.length ; i++)
		{
			icu.Verify(codeArray[i]);	
		}
	}
}
